package com._bytecode.__asm._ClassFieldRemove;

import com._bytecode.__asm.AsmUser;
import com._bytecode.__asm._ClassWriter.MyClassLoader;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassWriter;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;

/**
 * @Author: huangya
 * @Date: 2020/09/16
 * @Description:
 */
public class RemoveMethodTest {

    public static void main(String[] args) throws IOException, NoSuchMethodException, IllegalAccessException, InstantiationException, InvocationTargetException {
        InputStream inputStream = AsmUser.class.getResourceAsStream("AsmUser.class");
        byte[] b1 = new byte[inputStream.available()];
        inputStream.read(b1);

        ClassWriter cw = new ClassWriter(0);
        /** 删除getUserId方法 */
        RemoveMethodAdapter rma = new RemoveMethodAdapter(cw, "getUserId", "()Ljava/lang/String;");
        ClassReader cr = new ClassReader(b1);
        cr.accept(rma, 0);
        byte[] b2 = cw.toByteArray(); // b2 represents the same class as b1

        MyClassLoader myClassLoader = new MyClassLoader();
        Class c = myClassLoader.defineClass("com._bytecode.__asm.AsmUser", b2);

        /**
         * getUserId方法被删除，调用getUserId方法抛出java.lang.NoSuchMethodException异常
         */
        Object getUserId = c.getDeclaredMethod("getUserId").invoke(c.newInstance());
        System.out.println(getUserId);
    }
}
